<?php


class pagSeguroComponent extends Component{
	
	var $url = "https://ws.pagseguro.uol.com.br/v2/checkout";
	private $fields = "";
	
	
	private function fields($campo, $valor){			
		$this->fields[$campo]=iconv("UTF-8", "ISO-8859-1", $valor);
		
	}
	
	private function sendCurl(){
		// TODO VERIFICAR ERROS AQUI
		$c = curl_init($this->url);
		curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
		curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($c, CURLOPT_POST, true); // POST
		curl_setopt($c, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
		curl_setopt($c, CURLOPT_POSTFIELDS, $this->fields);
		curl_setopt($c, CURLOPT_ENCODING, 'UTF-8');
		curl_getinfo($c);
		$xml = curl_exec ($c);
		curl_close ($c);
		return $xml;
	}
	
	private function dadosUsuario($usuario){
		$estado = ClassRegistry::init('Estado');
		$estado = $estado->findById($usuario['uf']);
		$this->fields("senderName", $usuario['nome']);
		$this->fields("shippingType", 1);
		$this->fields("shippingAddressPostalCode", $usuario['cep']);
		$this->fields("shippingAddressStreet", $usuario['endereco']);
		$this->fields("shippingAddressNumber", $usuario['numero']);
		$this->fields("shippingAddressComplement", $usuario['complemento']);
		$this->fields("shippingAddressDistrict", $usuario['bairro']);
		$this->fields("shippingAddressCity", $usuario['cidade']);
		$this->fields("shippingAddressState", $estado['Estado']['sigla']);
		$this->fields("shippingAddressCountry", "BRA");
		$this->fields("senderAreaCode", $usuario['ddd']);
		$this->fields("senderPhone", $usuario['telefone']);
		$this->fields("senderEmail", $usuario['email']);
	}
	
	private function dadosCompra($dados){
		$this->fields('email', EMAIL_DEFAULT);
		$this->fields('token', TOKEN_PAG_SEGURO);
		$this->fields('currency', "BRL");
		$this->fields('tipo', "CP");
		$this->fields('itemId1', "0001");
		$this->fields('itemDescription1', $dados['descricao']);
		$this->fields('itemQuantity1', "1");
		$this->fields('itemAmount1', $dados['valor']);
		$this->fields('itemWeight1', "0");
	}
	
	private function geraCodigoXml($xml){
		$xml = simplexml_load_string($xml);pr($xml);
		return $xml->code;
	}
	
	public function efetuarPagamento($anuncio, $usuario, $dados_compra){
		$this->dadosUsuario($usuario);
		$this->dadosCompra($dados_compra);
		$this->fields =  http_build_query($this->fields);
		
		$xml = $this->sendCurl();
		return $this->geraCodigoXml($xml);
	}
	
}